package com.sunlands.deskmate.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.sunlands.deskmate.entity.DicDO;
import com.sunlands.deskmate.repository.DicRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author anjl
 * @date 6:23 PM 2019/7/11
 * description:
 */
@Slf4j
@Service
public class DicServiceImpl {
    public static Cache<String, DicDO> dicCache = CacheBuilder.newBuilder()
            .expireAfterWrite(60 * 10, TimeUnit.SECONDS)
            .maximumSize(5000)
            .build();

    public DicDO findByCode(final String code) {
        DicDO dic = dicCache.getIfPresent(code);
        if (Objects.nonNull(dic)) {
            return dic;
        }
        synchronized (code) {
            dic = find(code);
            dicCache.put(code, dic);
        }
        return dic;
    }

    private DicDO find(String code) {
        return dicRepository.findByCode(code);
    }

    public void clearCache() {
        dicCache.invalidateAll();
    }

    public void clearCache(String code){
        dicCache.invalidate(code);
    }

    @Autowired
    private DicRepository dicRepository;


}
